package scala.com.shujia.jichu

import scala.io.{BufferedSource, Source}

object Demo19WordCount {
  def main(args: Array[String]): Unit = {
    //1、读取数据文件,将每一行数据封装成集合的元素
    val lineList: List[String] = Source.fromFile("scala/data/words.txt").getLines().toList
    println(lineList)
    //2、将每一行数据按照|切分，并且进行扁平化
    val wordsList: List[String] = lineList.flatMap((line: String) => line.split("\\|"))
    println(wordsList)
    //3、根据元素进行分组
    val wordKV: Map[String, List[String]] = wordsList.groupBy((e: String) => e)
    println(wordKV)

    /**
     * List((world,8), (java,11),...)
     */
    val wordCount: Map[String, Int] = wordKV.map((kv: (String, List[String])) => {
      val word: String = kv._1
      val count: Int = kv._2.size
      (word, count)
    })

    println("="*50)
    val resultList: List[(String, Int)] = wordCount.toList
    resultList.foreach(println)
    println("="*50)

    /**
     * 使用链式调用的方式简写
     */
    Source.fromFile("scala/data/words.txt")
      .getLines()
      .toList
      .flatMap((line:String)=>line.split("\\|"))
      .groupBy((e:String)=>e)
      .map((kv: (String, List[String])) => {
        val word: String = kv._1
        val count: Int = kv._2.size
        (word, count)
      })
      .toList
      .foreach(println)
    println("=" * 50)

    /**
     * 使用链式调用的方式简写
     */
    Source.fromFile("scala/data/words.txt")
      .getLines()
      .toList
      .flatMap(_.split("\\|"))
      .groupBy((e:String)=>e)
      .map((kv: (String, List[String])) => (kv._1, kv._2.size))
      .toList
      .foreach(println)


  }
}
